package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.eKnowAi.EKnowKnowledgeBase;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.entity.eKnowAi.EKnowKnowledgeType;
import com.ys.entity.eKnowAi.EKnowTimerSet;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;
import com.ys.service.eKnowAi.EKnowTimerSetService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//定时表单分类绑定
@Controller
@RequestMapping("/api/inter/eKnowTimerSet")
public class ApiInterEKnowTimerSetController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterEKnowTimerSetController.class);

	@Autowired
	private CommonApiService<EKnowTimerSet> commonApiService;

	@Autowired
	private EKnowTimerSetService eKnowTimerSetService;
	@Autowired
	private EKnowKnowledgeListService eKnowKnowledgeListService;

	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public EKnowTimerSet setSeachSql(EKnowTimerSet cond){
		cond.addField("B.KnowledgeBaseName AS knowledgeBaseName");
		cond.addField("T.TypeName AS typeName");
		cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeType T ON A.TypeId = T.Id");
		cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON T.BaseId = B.Id");
		//排序
		cond.setOrderby("A.Sort ASC");
		return  cond;
	}


	/**
	 * 查询
	 */
	@RequiresPermissions("eKnowTimerSet:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
								 @ModelAttribute EKnowTimerSet cond
	){
		try {
			cond = setSeachSql(cond);
			LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
			return tableVoJA;
		}catch (Exception e){
			logger.error("查询日志出错：",e.getMessage(),e);
			LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
			tableVoJA.setCode(1);
			tableVoJA.setMsg("查询出错，请稍后重试！");
			return tableVoJA;
		}
	}


	/**
	 *	查询定时表单分类相关信息
	 */
	@PostMapping("/searchEKnowTimerSetById")
	@ResponseBody
	public JSONObject searchEKnowTimerSetById(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());//知识库Id
			EKnowTimerSet eKnowTimerSet = new EKnowTimerSet()
					.where("A.Id = "+id)
					.queryFirst();
			if(eKnowTimerSet!=null){
				List<EKnowKnowledgeType> eKnowKnowledgeTypeList = new EKnowKnowledgeType().setOrderby("A.Sort ASC").queryList();
				List<EKnowKnowledgeBase> eKnowKnowledgeBaseList = new EKnowKnowledgeBase().setOrderby("A.Sort ASC").queryList();
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				result.put("eKnowTimerSet", eKnowTimerSet);
				result.put("eKnowKnowledgeTypeList", eKnowKnowledgeTypeList);
				result.put("eKnowKnowledgeBaseList", eKnowKnowledgeBaseList);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("查询定时表单分类相关信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 * 修改定时表单分类绑定
	 */
	@PostMapping("/updateEKnowTimerSet")
	@ResponseBody
	public JSONObject updateEKnowTimerSet(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());//Id
			String timerName = params.get("timerName").toString();//名称
			long typeId = Long.parseLong(params.get("typeId").toString());//所属分类
			long baseId = Long.parseLong(params.get("baseId").toString());//所属知识库
			int sort = Integer.parseInt(params.get("sort").toString());//排序
			int isSave = 0;
			EKnowTimerSet eKnowTimerSetOld = new EKnowTimerSet().setId(id).queryFirst();
			if(eKnowTimerSetOld!=null){
				int isUpdate = 0;
				//如果有切换知识库，那么向量数据库也需要同步切换
				if(eKnowTimerSetOld.getBaseId()!=baseId){
					List<EKnowKnowledgeList> eKnowKnowledgeList = new EKnowKnowledgeList().setInfoMark(eKnowTimerSetOld.getTimerKey()).queryList();
					List<Map<String, Object>> getKnowLedgeListSectionIdByInfoMark = eKnowTimerSetService.getKnowLedgeListSectionIdByInfoMark(eKnowTimerSetOld.getTimerKey());
					if(eKnowKnowledgeList!=null && eKnowKnowledgeList.size()>0
							&& getKnowLedgeListSectionIdByInfoMark!=null && getKnowLedgeListSectionIdByInfoMark.size()>0){
						//删除
						for(EKnowKnowledgeList item:eKnowKnowledgeList){
							eKnowKnowledgeListService.deleteKnowledgeListWithES(item.getId());
						}
						//新增
						if(eKnowTimerSetOld!=null){
							for(Map<String, Object> markItem:getKnowLedgeListSectionIdByInfoMark){
								String sectionId = markItem.get("SectionId").toString();
								List<EKnowKnowledgeList> eKnowKnowledgeListByInfoMark = eKnowKnowledgeList.stream().filter(item->item.getSectionId().equals(sectionId)).collect(Collectors.toList());
								List<String> informationList = new ArrayList<>();
								for(EKnowKnowledgeList item:eKnowKnowledgeListByInfoMark){
									informationList.add(item.getInformation());
								}
								String loginUserId = ShiroUtils.getUserId();//登录的用户ID
								isUpdate = eKnowKnowledgeListService.addKnowledgeListByList3(baseId,typeId,informationList,sectionId,eKnowTimerSetOld.getTimerKey(),loginUserId);
							}
						}
					}else {
						isUpdate = 1;
					}
				}else {
					isUpdate = 1;
				}
				if(isUpdate>0){
					EKnowTimerSet eKnowTimerSet = new EKnowTimerSet();
					eKnowTimerSet.setId(id);
					eKnowTimerSet.setTimerName(timerName);
					eKnowTimerSet.setTypeId(typeId);
					eKnowTimerSet.setSort(sort);
					eKnowTimerSet.setBaseId(baseId);
					isSave = eKnowTimerSetService.update(eKnowTimerSet);
				}
			}
			if(isSave>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道新增、修改知识库分类信息出错：",e.getMessage(),e);
		}
		return result;
	}







}